import React, { useState, useEffect } from "react";
import Modal from "antd/lib/modal";
import Form from "antd/lib/form";
import Tree from 'antd/lib/tree';
import Transfer from 'antd/lib/transfer';
import { wrap as wrapDialog, DialogPropType } from "@/components/DialogWrapper";
import DynamicComponent from "@/components/DynamicComponent";
import { UserProfile } from "@/components/proptypes";
import notification from "@/services/notification";
import { currentUser } from "@/services/auth";
import QueryShowField from "@/services/queryshowfield";
import zhCN from 'antd/es/locale/zh_CN';
import ConfigProvider from "antd/lib/config-provider";

function CreateQueryShowFieldDialog({ queryshowfield, dialog }) {
  const [dataLoaded, setDataLoaded] = useState(queryshowfield.id === 0 ? true : false);
  const [code, setCode] = useState("");
  const [name, setName] = useState("");
  const [treedata, settreedata] = useState([]);

  const [fieldsshow, setfieldsshow] = useState([]);
  const [fieldsall, setfieldsall] = useState([]);
  const [message, setmessage] = useState("");
  const [isValid, setIsValid] = useState(false);
  const [saveInProgress, setSaveInProgress] = useState(false);
  const isCreateQueryShowFieldEnabled = useState(true);//policy.isAdmin() || policy.isDefault();

  useEffect(() => {
    if (queryshowfield.id === 0) return;
    setCode(queryshowfield.code);
    setName(queryshowfield.name);
    setfieldsshow(queryshowfield.fieldsshow);
    setfieldsall(queryshowfield.fieldsall);
    setmessage(queryshowfield.message);
    setDataLoaded(true);
    let transferDataSource = [];
    queryshowfield.fieldsshow.forEach((key) => {
      let item = queryshowfield.fieldsall.filter((p) => {
        return p.key === key;
      });
      if (item.length > 0) {
        transferDataSource.push(item[0]);
      }
    });
    settreedata(transferDataSource);
  }, [queryshowfield]);

  // function handlefieldsshowChange(event) {
  //   setfieldsshow(event);
  //   setIsValid(event !== "");
  // }

  function handleSubmit() {
    setSaveInProgress(true);
    let showfieldtemp = [];
    (treedata || []).map(item => {
        showfieldtemp.push(item.key);
      return item;
    }
    );
    let data = {
      id: queryshowfield.id,//
      userid: currentUser.id,//--操作员ID
      code: code,
      name: name,
      fieldsshow: showfieldtemp,
      fieldsall: fieldsall,
      message: message
    }
    QueryShowField.save(data)
      .then(() => {
        dialog.close({ success: true });
      })
      .catch(error => {
        notification.error(error.message, error.detailedMessage);
        setSaveInProgress(false);
      });
  }

  const isChecked = (selectedKeys, eventKey) => selectedKeys.includes(eventKey);

  const onChange = (keys) => {
    let transferDataSource = [];
    keys.forEach((key) => {
      let item = fieldsall.filter((p) => {
        return p.key === key;
      });
      if (item.length > 0) {
        transferDataSource.push(item[0]);
      }
    });
    setfieldsshow(keys);
    setIsValid(keys !== "");
    settreedata(transferDataSource);
  };
  const onDrop = info => {
    const dropKey = info.node.props.eventKey;
    const dragKey = info.dragNode.props.eventKey;
    const dropPos = info.node.props.pos.split('-');
    const dropPosition = info.dropPosition - Number(dropPos[dropPos.length - 1]);

    const loop = (data, key, callback) => {
      data.forEach((item, index, arr) => {
        if (item.key === key) {
          return callback(item, index, arr);
        }
        if (item.children) {
          return loop(item.children, key, callback);
        }
      });
    };
    const data = [...treedata];

    // Find dragObject
    let dragObj;
    loop(data, dragKey, (item, index, arr) => {
      arr.splice(index, 1);
      dragObj = item;
    });

    if (!info.dropToGap) {
      // Drop on the content
      loop(data, dropKey, item => {
        item.children = item.children || [];
        // where to insert 示例添加到尾部，可以是随意位置
        item.children.push(dragObj);
      });
    } else if (
      (info.node.props.children || []).length > 0 && // Has children
      info.node.props.expanded && // Is expanded
      dropPosition === 1 // On the bottom gap
    ) {
      loop(data, dropKey, item => {
        item.children = item.children || [];
        // where to insert 示例添加到头部，可以是随意位置
        item.children.unshift(dragObj);
      });
    } else {
      let ar;
      let i;
      loop(data, dropKey, (item, index, arr) => {
        ar = arr;
        i = index;
      });
      if (dropPosition === -1) {
        ar.splice(i, 0, dragObj);
      } else {
        ar.splice(i + 1, 0, dragObj);
      }
    }
    window.console.log('onDrop', data);
    setIsValid(fieldsshow !== "");
    settreedata(data);
  };
  return (
    <Modal
      {...dialog.props}
      {...(isCreateQueryShowFieldEnabled ? {} : { footer: null })}
      title="列表显示隐藏列管理"
      width={document.querySelector('body').offsetWidth * 0.4}
      okText="保存"
      cancelText="取消"
      okButtonProps={{
        disabled: !isValid || saveInProgress,
        loading: saveInProgress,
        "data-test": "DashboardSaveButton",
      }}
      cancelButtonProps={{
        disabled: saveInProgress,
      }}
      onOk={handleSubmit}
      closable={!saveInProgress}
      maskClosable={!saveInProgress}
      wrapProps={{
        "data-test": "CreateDashboardDialog",
      }}>
      {dataLoaded && (
        <ConfigProvider locale={zhCN}>
          <DynamicComponent name="CreateQueryShowFieldDialogExtra" disabled={!isCreateQueryShowFieldEnabled}>
            <Form layout="horizontal" {...{ labelCol: { span: 4 }, wrapperCol: { span: 14 }, }}>
              {/* <Form.Item style={{ marginBottom: 5 }} label="编码">
              <Input
                defaultValue={code}
                placeholder="编码"
                disabled={true}
              />
            </Form.Item>
            <Form.Item style={{ marginBottom: 5 }} label="名称">
              <Input
                defaultValue={name}
                placeholder="名称"
                disabled={true}
                autoFocus
              />
            </Form.Item> */}
              <Form.Item style={{ marginBottom: 5 }} label="字段">
                <Transfer
                  targetKeys={fieldsshow}
                  titles={['隐藏', '显示']}
                  dataSource={fieldsall}
                  className="tree-transfer"
                  render={(item) => item.title}
                  showSelectAll={false}
                  onChange={onChange}
                >
                  {({ direction, onItemSelect, selectedKeys }) => {
                    if (direction === 'right') {
                      const checkedKeys = [...selectedKeys];
                      return (
                        <div
                        >
                          <Tree
                            blockNode
                            checkable
                            draggable
                            checkStrictly
                            defaultExpandAll
                            checkedKeys={checkedKeys}
                            treeData={treedata}
                            onCheck={(_, { node: { key } }) => {
                              onItemSelect(key, !isChecked(checkedKeys, key));
                            }}
                            onSelect={(_, { node: { key } }) => {
                              onItemSelect(key, !isChecked(checkedKeys, key));
                            }}
                            onDrop={onDrop}
                          />
                        </div>
                      );
                    }
                  }}
                </Transfer>
              </Form.Item>
              {/*<Form.Item style={{ marginBottom: 5 }} label="字段">
              <Checkbox.Group
                style={{ width: '100%' }}
                defaultValue={fieldsshow}
                onChange={handlefieldsshowChange}>
                &nbsp;&nbsp;&nbsp;
                {map(fieldsall, ds => (
                  <Checkbox style={{ width: "160px" }} value={ds.key}>{ds.title}</Checkbox>
                ))}

              </Checkbox.Group>
            </Form.Item> */}
              {/* <Form.Item style={{ marginBottom: 5 }} label="备注">
              <TextArea
                value={message}
                placeholder="备注"
                autoSize={{ minRows: 3, maxRows: 5 }}
              />

            </Form.Item> */}
            </Form>
          </DynamicComponent>
        </ConfigProvider>
      )}
    </Modal>
  );
}

CreateQueryShowFieldDialog.propTypes = {
  QueryShowField: UserProfile.isRequired,
  dialog: DialogPropType.isRequired,
};

export default wrapDialog(CreateQueryShowFieldDialog);
